<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="query.name" placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="searchFn">查询</el-button>
    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="id ? '编辑楼宇' : '添加楼宇'"
      :visible="dialogVisible"
      @close="closeDialog"
    >

      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="buildForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="addNewBuilding">确 定</el-button>
      </template>
    </el-dialog>

    <el-button v-auth-dir="`park:building:add_edit`" type="primary" @click="addBuilding">添加楼宇</el-button>
    <el-button @click="exportToExcel">导出Excel</el-button>
    <!-- 表格区域 -->
    <div v-auth-dir="`park:building:list`" class="table">
      <el-table
        style="width: 100%"
        :data="buildData"
      >
        <el-table-column
          type="index"
          prop="index"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
          :formatter="formatterFn"
        />
        <el-table-column
          label="操作"
        >
          <template #default="scoup">
            <el-button
              v-auth-dir="`park:building:add_edit`"
              size="mini"
              type="text"
              @click="editBuilding(scoup.row.id)"
            >编辑</el-button>
            <el-button
              v-auth-dir="`park:building:remove`"
              size="mini"
              type="text"
              @click="delBuilding(scoup.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-container">
        <el-pagination
          layout="total, prev, pager, next"
          :total="total"
          :current-page.sync="currentpage"
          :page-size="query.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingListAPI, modifyBuildingListAPI } from '@/apis/build'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      buildData: [],
      query: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0, // 总条数
      currentpage: 1, // 当前页
      dialogVisible: false,
      id: '',
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼栋名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入建筑面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入物业费单价', trigger: 'blur' }
        ]
      },
      headerData: {
        'id': '序号',
        'name': '楼宇名称',
        'floors': 'c层数',
        'area': '在管面积(m²)',
        'propertyFeePrice': '物业费(元/m²)',
        'status': '状态'
      },
      statusObj: {
        0: '空置',
        1: '租赁中'
      }
    }
  },
  created() {
    this.getBuilding()
  },
  methods: {
    async getBuilding() {
      const res = await getBuildingListAPI(this.query)
      this.buildData = res.data.rows
      this.total = res.data.total
    },
    formatterFn(row) {
      // 字典对象

      return this.statusObj[row.status]
    },
    // 分页下拉列表
    handleSizeChange(val) {
      this.query.pageSize = val
      this.currentpage = 1
      this.handleCurrentChange()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getBuilding()
    },
    // 搜索功能
    searchFn() {
      this.query.page = 1
      this.getBuilding()
    },
    // 打开弹窗
    addBuilding() {
      this.dialogVisible = true
    },
    // 关闭弹窗
    closeDialog() {
      this.$refs.buildForm.resetFields()
      this.id = ''
      this.dialogVisible = false
    },
    // 添加楼宇功能 和编辑功能
    async addNewBuilding() {
      if (this.id) {
        // 编辑功能
        this.$refs.buildForm.validate()
        const obj = { id: this.id, ...this.addForm }
        console.log(obj)
        const res = await modifyBuildingListAPI(obj)
        console.log(res)
        this.id = ''
      } else {
        // 新增功能
        this.$refs.buildForm.validate()
        await createBuildingListAPI(this.addForm)
      }
      this.query.page = 1
      this.getBuilding()
      this.$refs.buildForm.resetFields()
      this.dialogVisible = false
    },
    // 删除楼宇功能
    async delBuilding(id) {
      this.$confirm('此操作将永久删除该楼宇, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delBuildingListAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.query.page = 1
        this.getBuilding()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑弹窗
    async editBuilding(id) {
      this.dialogVisible = true
      this.id = id
      const res = await editBuildingListAPI(id)
      console.log(res)
      this.addForm.name = res.data.name
      this.addForm.floors = res.data.floors
      this.addForm.area = res.data.area
      this.addForm.propertyFeePrice = res.data.propertyFeePrice
    },
    // 导出Excel
    // 获取计费规则
    exportToExcel() {
      // 目标：解决表格每行数据的先后顺序
      // 顺序取决于对象属性的 Object.keys() 拿出来的顺序
      // 知识：Object.keys() 按照对象属性添加的先后顺序获取成属性集合数组,但是如果属性有数字则会放到前面按照值大小顺序收集（不要让对象有数字属性）
      // 思路：把后台给我的数组对象，按照我组织的key的先后顺序，往空白对象里添加（插件内的方法 Object.keys() 取对象属性时就能按照我插入的先后顺序来获取赋予表格里的值）
      const keys = ['id', 'name', 'floors', 'area', 'propertyFeePrice', 'status']
      const newDataList = this.buildData.map((item, index) => {
        const newObj = {}
        keys.forEach(keyStr => {
          if (keyStr === 'status') {
            newObj[keyStr] = this.statusObj[item[keyStr]]
          } else if (keyStr === 'id') {
            newObj[keyStr] = index + 1
          } else {
            newObj[keyStr] = item[keyStr]
          }
        })
        return newObj
      })
      // 1. 创建一个新的工作簿
      const workbook = utils.book_new()
      // 2. 创建一个工作表 要求一个对象数组格式（可以根据需要创建多个）
      const worksheet = utils.json_to_sheet(newDataList)
      // 3. 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, '楼宇管理')
      // 改写表头
      // 对象字段属性数组 => 中文字符串数组
      // 遍历 keys 数组顺序遍历，映射的中文名肯定按照顺序的
      const headerList = keys.map(item => this.headerData[item])
      utils.sheet_add_aoa(worksheet, [headerList], { origin: 'A1' })
      // 4. 导出方法进行导出
      writeFileXLSX(workbook, '园区管理-楼宇管理.xlsx')
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.page-container{
    padding:4px 0px;
    text-align: right;
  }
</style>
